﻿Namespace Core
    Public Class Album

        Private _Baseuri As Uri
        Private _PreviewList As List(Of Uri)
        Private _Images As List(Of Uri)
        Private _AlbumTitle As String


        Public Sub New(ByVal Uri As Uri)
            If Uri.IsFile Then 'Is a local file
                Dim xDoc As XDocument = XDocument.Load(Uri.LocalPath)

                'Get the title of the album
                _AlbumTitle = xDoc.<ImageList>.@Title

                'Get the images in the album
                _Images =
                    (From item In xDoc...<ImageList>.<Image> Select New Uri(item.Value)).ToList

                'Take 3 images to create the preview list
                _PreviewList = _Images.Take(3).ToList

            Else 'Is a remote file.

                Dim Loader As New Net.WebClient
                Loader.DownloadStringAsync(Uri)

                AddHandler Loader.DownloadStringCompleted,
                    Sub(s As Object,
                        e As System.Net.DownloadStringCompletedEventArgs)

                        Dim xDoc = XDocument.Load(e.Result)

                        'Get the title
                        _AlbumTitle = xDoc.<ImageList>.@Title

                        'Loads all the images in the album
                        _Images =
                            (From item In xDoc...<ImageList>.<Image> Select New Uri(item.Value)).ToList

                        'Take 3 images to create the preview list.
                        _PreviewList = _Images.Take(3).ToList

                    End Sub
            End If

            _Baseuri = Uri

        End Sub

        Public Sub SaveList()
            If _Baseuri.IsFile Then
                Dim Xml = <ImageList>
                              <%= From item In _Images
                                  Select <Image><%= item.AbsoluteUri %></Image>
                              %>
                          </ImageList>
                Dim sw As New IO.StreamWriter(_Baseuri.LocalPath)
                sw.Write(Xml.ToString)
                sw.Close()
            Else
                Throw New Exception("File is not local")
            End If
        End Sub

        Public ReadOnly Property Images As List(Of Uri)
            Get
                Return _Images
            End Get
        End Property

        Public ReadOnly Property PreviewImages As List(Of Uri)
            Get
                Return _PreviewList
            End Get
        End Property

        Public ReadOnly Property BaseUri As Uri
            Get
                Return _Baseuri
            End Get
        End Property

        Public Property AlbumTitle
            Get
                Return _AlbumTitle
            End Get
            Set(ByVal value)
                _AlbumTitle = value
            End Set
        End Property

    End Class
End Namespace
